home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12586 < prev    next >
Encoding:
Text File  |  1996-08-05  |  51.6 KB  |  1,677 lines

  1. Path: solon.com!not-for-mail
  2. From: seebs@solutions.solon.com (Peter Seebach)
  3. Newsgroups: comp.lang.c,comp.lang.c.moderated,news.answers
  4. Subject: comp.lang.c Answers to Infrequently Asked Questions (FAQ List)
  5. Followup-To: poster
  6. Date: 1 Apr 1996 15:34:19 -0600
  7. Organization: Usenet Fact Police (Undercover)
  8. Approved: seebs@solon.com
  9. Message-ID: <4jpi4r$6fs@solutions.solon.com>
  10. NNTP-Posting-Host: solutions.solon.com
  11. Summary: Questions and Answers.
  12. X-Last-Modified: April 1, 1996
  13.  
  14. [Last modified April 1, 1996 by seebs.] [Revision: yes]
  15.  
  16. [Copyright 1995, 1996 Peter Seebach.  All rights reserved, all wrongs reversed.
  17.  Unauthorized duplication and distribution prohibited.]
  18.  
  19. Certain topics never (well, hardly ever) come up on this newsgroup.
  20. They are stupid questions, to which the answers are immediately obvious,
  21. but they would be more fun to talk about than these arcane details of
  22. loop control.
  23.  
  24. This article, which is posted yearly, attempts to answer these questions
  25. definitively, succinctly, and in such a way as to discourage further
  26. discussion.
  27.  
  28.      1. Declarations and Initializations
  29.      2. Structures, Unions, and Enumerations
  30.      3. Expressions
  31.      4. Null Statements
  32.      5. Arrays and Pointers
  33.      6. Memory Allocation
  34.      7. Boolean Expressions and Variables
  35.      8. C Preprocessor
  36.      9. ANSI/ISO Standard C
  37.     10. Stdio
  38.     11. Library Functions
  39.     12. Floating Point
  40.     13. Variable-Length Argument Lists
  41.     14. Lint
  42.     15. Strange Problems
  43.     16. Style
  44.     17. System Dependencies
  45.     18. Miscellaneous
  46.  
  47. Questions marked with a leading asterisk (``*'') indicate answers I have seen
  48. given as real answers, by particularly ignorant posters in comp.lang.c.
  49. (This added to immortalize a user I recently discovered, whose answers
  50. to questions sometimes border on the surreal.  Name/email address
  51. available by request.)
  52.  
  53. Herewith, some infrequently-asked questions and their answers:
  54.  
  55. Section 1. Declarations and Initializations
  56.  
  57. 1.1:    How do you decide which integer type to use?
  58.  
  59. A:    Use ``short'' when you need to avoid values over 32,767, ``int'' when
  60.     you want to store integers, ``long'' for long numbers (more than 6
  61.     digits), and ``float'' for numbers over 4 billion.
  62.  
  63. 1.2:    What should the 64-bit type on new, 64-bit machines be?
  64.  
  65. A:    int.
  66.  
  67. 1.3:    If I write the code
  68.  
  69.         int i, j;
  70.     
  71.     can I assume that (&i + 1) == &j?
  72.  
  73. A:    Only sometimes.  It's not portable, because in EBCDIC, i and j are
  74.     not adjacent.
  75.  
  76. 1.4:    What's the best way to declare and define global variables?
  77.  
  78. A:    In headers; this way, you can get link errors when you include the
  79.     same header twice.  Generally, you will have to define a variable
  80.     everywhere you want to use it, and then declare it someplace so
  81.     you know what it is.
  82.  
  83. 1.5:    What does extern mean in a function declaration?
  84.  
  85. A:    It refers to a variable which is not actually in your program.  For
  86.     instance,
  87.  
  88.         main() {
  89.             extern int bar;
  90.             printf("%d\n", bar);
  91.             return 0;
  92.         }
  93.  
  94.     will compile without errors because bar is declared as being
  95.     external.  (It won't run, though, because you never assign bar a
  96.     value.)
  97.  
  98. 1.6:    I finally figured out the syntax for declaring pointers to
  99.     functions, but now how do I initialize one?
  100.  
  101. A:    With the assignment operator.  You were perhaps expecting
  102.     a screwdriver?
  103.  
  104. 1.7:    I've seen different methods used for calling through pointers to
  105.     functions.  What's the story?
  106.  
  107. A:    In the old days, when Microsoft first invented C, the syntax for
  108.     calling functions involved more parentheses; this was after their
  109.     market research indicated that most C programmers would be
  110.     coming from a Lisp environment.  Later, when Kernighan took
  111.     over the language design (right after AT&T bought Microsoft's
  112.     language technology), he decided to eliminate the parentheses,
  113.     but the old form is still allowed.
  114.  
  115.     You do need the parentheses to call a function with more than
  116.     one argument, for instance,
  117.  
  118.         int (*foo)(char *, ...) = printf;
  119.  
  120.         (*foo)("hello, %s\n", "world!");
  121.  
  122.     needs the parens, but they would not be needed for
  123.  
  124.         foo, "hello, world!\n";
  125.  
  126.     (The ``*'' just means to execute foo, just like the ``*'' on the end
  127.     of an executable filename in ``ls -F''.)
  128.  
  129. 1.8:    What's the auto keyword good for?
  130.  
  131. A:    Declaring vehicles.
  132.  
  133. 1.9:    I can't seem to define a linked list successfully.  I tried
  134.  
  135.         typedef struct {
  136.             char *item;
  137.             NODEPTR next;
  138.         } *NODEPTR;
  139.  
  140.     but the compiler gave me error messages.  Can't a structure in C
  141.     contain a pointer to itself?
  142.  
  143. A:    Not exactly; it can contain a pointer to another structure of the
  144.     same type.  Try:
  145.  
  146.         typedef struct {
  147.             char *item;
  148.             double *next;
  149.         } NODEFAKE;
  150.  
  151.         typedef struct {
  152.             char *item;
  153.             NODEFAKE *next;
  154.         } NODEPTR;
  155.  
  156.     Make sure that sizeof(NODEPTR) == sizeof(double).
  157.  
  158.     This technique is called a ``backwards reference''.
  159.  
  160. 1.10:    How do I enter values using hexadecimal?
  161.  
  162. A:    long ints can be entered using hexadecimal notation; for instance,
  163.  
  164.         long int foo = 07;
  165.  
  166.     sets foo to hex 7.
  167.  
  168. 1.11:    How do I declare an array of N pointers to functions returning
  169.     pointers to functions returning pointers to characters?
  170.  
  171. A:    Well, first you need to know how to declare an array of N
  172.     items of type T - that's
  173.  
  174.         T foo[N];
  175.  
  176.     Now you need to look at how to declare a pointer to function
  177.     returning something, say, an object of type S.  That's like this:
  178.  
  179.         S (*bar)();
  180.  
  181.     Now assume that S is ``pointer to function returning pointer to
  182.     char''.  We get
  183.  
  184.         (char *) (*)() (*bar)().
  185.  
  186.     So, the whole thing turns out to be (with appropriate parentheses)
  187.  
  188.         (((char)(*))((*)())(((*)((foo)))())([(N))]);
  189.  
  190.     If your compiler complains, break this down into subexpressions.
  191.  
  192.     To call it, just use
  193.  
  194.         foo[i]();
  195.  
  196.     This works because, in C, declaration reflects use, but it's one
  197.     of those weird distorted mirrors.
  198.  
  199.  
  200. Section 2. Structures, Unions, and Enumerations
  201.  
  202. 2.1:    What is the difference between an enum and a series of
  203.     preprocessor #defines?
  204.  
  205. A:    The enum doesn't require the preprocessor.
  206.  
  207. 2.2:    I heard that structures could be assigned to variables and
  208.     passed to and from functions, but K&R I says not.
  209.  
  210. A:    K&R I was wrong; they hadn't actually learned C very well before
  211.     writing the book.  Later, Ritchie got a job at Bell Labs, and worked
  212.     closely with the authors of C, allowing the 2nd edition of the book
  213.     to be much more accurate.  (Kernighan already worked at Bell Labs,
  214.     where he helped develop the ``kaw'' programming language, used to
  215.     simulate crows in an international chess tournament.)
  216.  
  217. 2.3:    How does struct passing and returning work?
  218.  
  219. A:    The structures are put into the low part of the VGA card's VRAM.
  220.     They are then removed before the next video update.  This is why
  221.     struct passing was not supported for a long time; VGA cards were
  222.     prohibitively expensive.
  223.  
  224.     If you try to pass very large structures on the stack, you may see
  225.     odd screen graphics.
  226.  
  227. 2.4:    Why can't you compare structs?
  228.  
  229. A:    Compare them to what?  A summer's day?
  230.  
  231. 2.5:    How can I read/write structs from/to data files?
  232.  
  233. A:    Loop with putchar.  Be careful; if your machine uses signed chars
  234.     by default, all of the sign bits in your structure elements will
  235.     be reversed.
  236.  
  237. 2.6:    How can I determine the byte offset of a field within a
  238.     structure?
  239.  
  240. A:    It's generally 4 times the number of members of the structure.
  241.     It may be more or less on some machines.
  242.  
  243. 2.7:    How can I access structure fields by name at run time?
  244.  
  245. A:    foo."name" should work.  You may need to overload the . operator,
  246.     which, in turn, may overload your C compiler.
  247.  
  248. 2.8:    Why does sizeof report a larger size than I expect for a
  249.     structure type, as if there was padding at the end?
  250.  
  251. A:    Because there's padding at the end.  *DUH*.
  252.  
  253. 2.9:    My compiler is leaving holes in structures, which is wasting
  254.     space and preventing ``binary'' I/O to external data files.  Can I
  255.     turn off the padding, or otherwise control the alignment of
  256.     structs?
  257.  
  258. A:    Sure.  What you do to eliminate the padding in structures is use
  259.     unions; for intance,
  260.  
  261.         struct foo {
  262.             char c;
  263.             long l;
  264.             char d;
  265.             char e;
  266.             char f;
  267.         };
  268.  
  269.     may cause struct foo to be padded to 12 bytes, rather than the
  270.     correct size of 8.  Try
  271.  
  272.         union foo {
  273.             double _d;
  274.             char c, d, e, f;
  275.             long l;
  276.         };
  277.  
  278.     which will be 8 bytes.  (The double is for alignment.)
  279.  
  280. 2.10:    Can I initialize unions?
  281.  
  282. A:    Depends.  They may go on strike when provoked.  Luckily, if your
  283.     program involves air traffic control, the ISO standard guarantees
  284.     that Ronald Reagan will fire any unions that go on strike, and
  285.     replace them with structs, which should be close enough.
  286.  
  287. 2.11:    How can I pass constant values to routines which accept struct
  288.     arguments?
  289.  
  290. A:    Try foo((struct foo) 3).
  291.  
  292.  
  293. Section 3. Expressions
  294.  
  295. 3.1:    Why doesn't this code:
  296.  
  297.         a[i] = i++;
  298.  
  299.     work?
  300.  
  301. A:    You didn't declare either i or a.
  302.  
  303. 3.2:    Under my compiler, the code
  304.  
  305.         int i = 7;
  306.         printf("%d\n", i++ * i++);
  307.  
  308.     prints 49.  Regardless of the order of evaluation, shouldn't it
  309.     print 56?
  310.  
  311. A:    No.  The only logical answer would be 81 - two postfix ++'s are
  312.     automatically converted to prefix.
  313.  
  314. 3.3:    I've experimented with the code
  315.  
  316.         int i = 2;
  317.         i = i++;
  318.  
  319.     on several compilers.  Some gave i the value 2, some gave 3, but
  320.     one gave 4.  I know the behavior is undefined, but how could it
  321.     give 4?
  322.  
  323. A:    Because i is 2, the loop is executed twice.
  324.  
  325. 3.4:    People keep saying the behavior is undefined, but I just tried
  326.     it on an ANSI-conforming compiler, and got the results I
  327.     expected.
  328.  
  329. A:    They were probably wrong.  Flame them mercilessly.  Be sure before
  330.     you do that your compiler is really* ANSI conforming, though.  If
  331.     it turns out you were wrong, they get a legal claim on your first-born.
  332.  
  333. 3.5:    Can I use explicit parentheses to force the order of evaluation
  334.     I want?  Even if I don't, doesn't precedence dictate it?
  335.  
  336. A:    No.  To force order of evaluation, you must threaten it.  Take the
  337.     comma operator hostage.  Using it, you can force the other operators
  338.     to do what you want.
  339.  
  340. 3.6:    But what about the &&, ||, and comma operators?
  341.     I see code like ``if((c = getchar()) == EOF || c == '\n')'' ...
  342.  
  343. A:    As noted, once you've captured the comma operator, the others
  344.     become docile.
  345.  
  346. 3.7:    If I'm not using the value of the expression, should I use i++
  347.     or ++i to increment a variable?
  348.  
  349. A:    ++i.  Only losers and idiots use i++.  This is different if your
  350.     native language would idiomatically use ``i increment'', but in
  351.     English and related languages, you must use ``++i''.  Note that
  352.     a modern program must use both, dependent on the current locale.
  353.  
  354. 3.8:    Why is i = ++i undefined?
  355.  
  356. A:    Because it is unclear whether it is shorthand for
  357.  
  358.         i = 42;
  359.     
  360.     or
  361.  
  362.         i = (char *) "forty two";
  363.     
  364.     Given the ambiguity, the standards committee decided to leave it
  365.     undefined.
  366.  
  367.  
  368. Section 4. Null Statements
  369.  
  370. 4.1:    What is this infamous null statement, anyway?
  371.  
  372. A:    A null statement is an expression statement consisting solely
  373.     of the terminating semicolon.  The optional expression is dropped.
  374.     It can be distinguished from any other statement by byte count
  375.     or study of side-effects.
  376.  
  377. 4.2:    How do I ``get'' a null statement in my programs?
  378.  
  379. A:    In ANSI C, there are six types of statements; labeled statements,
  380.     compound statements, expression-statements, selection statements,
  381.     iteration statements, and jump statements.  All of them, except
  382.     the jump and expression statments, are defined in terms of optional
  383.     preceeding text, and other statements.  The jump statements are
  384.     never null statements.  An expression statement is considered to
  385.     be ``a null statement'' if the optional expression part of it has
  386.     been left out.  A null statement can appear on its own, or (most
  387.     frequently) as the statement body of an iteration statement.  These
  388.     two null statements are equivalent, though neither of them is
  389.     equivalent to any non-null statement.  [*]
  390.  
  391.     You may accidentally get a null statement by deleting the body of
  392.     a non-null statement.
  393.  
  394.     [*] Actually, they are functionally equivalent to a large set of
  395.     non-null statements, namely, those with no side-effects.  However,
  396.     the FDA has yet to approve any such, as their lack of side effects
  397.     is conjectured, and not clinically proven.  This applies only to
  398.     the ANSI standard, and not the ISO standard, as the FDA has no
  399.     jurisdiction outside the U.S.
  400.  
  401. 4.3:    Is there more than one null statement?
  402.  
  403. A:    Sort of.  You can use
  404.         ;
  405.     or
  406.         0;
  407.     or
  408.         1;
  409.     - they will all act like a null statement.  Only the first is
  410.     a ``true'' null statement (all bits zero).  They are basically
  411.     equivalent.  Note that (void *) 0; is a null statement of type
  412.     pointer to void, for instance.
  413.  
  414. 4.4    But I thought { } was a null statement!
  415.  
  416. A:    No.  { statement-list[opt] } is a compound statement.  An empty
  417.     block is not the same as a null statement, however, although it
  418.     can be used in many of the same places.  It's really a null
  419.     block.  (You can convert it with a cast, but it's not directly
  420.     compatible.  For instance, you can't use a null block as one
  421.     of the controlling statements of a for loop.)
  422.  
  423. 4.5    I use the statement
  424.         #define NULLSTMT(F)    (F) ;
  425.     to allow me to cast a null statement to an appropriate type.
  426.  
  427. A:    This trick, though popular in some circles, does not buy much.
  428.     The resulting code is illegal, and will not compile.  This (in
  429.     the author's opinion) outweighs any arguable type consistency.
  430.     It may be more common in industrial code.  If it becomes common
  431.     practice, C++ will probably legalize it.
  432.  
  433. 4.6    I use the statement
  434.         #define NULLSTMT(F)    (F) 0;
  435.     to allow me to cast a null statement to an appropriate type.
  436.  
  437. A:    This trick will likely work, but think: what does it really buy
  438.     you?  Mostly, it will indicate to even the most casual observer
  439.     that you are shakey on the concept of null statements, making it
  440.     harder for them to check your code.
  441.  
  442. 4.7:    But wouldn't it be better to use ``;'' (rather than ``0;'') in case
  443.     the value of 0 changes, perhaps on a machine with nonzero
  444.     no-op instructions?
  445.  
  446. A:    No.  The ``0'' of ``0;'' is not evaluated as an instruction, rather,
  447.     it is just ignored.  The advantages of ``;'' over ``0;'' have only to
  448.     do with poor optimizers and savings of keystrokes.
  449.  
  450. 4.8:    Is a null statement a null pointer?
  451.  
  452. A:    No.  A null pointer is a pointer where all of the address bits
  453.     are zero (no matter what the segment bits are), and can be
  454.     obtained by typing '(char *) (int) 0'.  A null statement is
  455.     not a pointer to anything.  They are not interchangeable, although
  456.     you can combine them to get an effectively-null statement, such
  457.     as
  458.  
  459.         NULL;
  460.     
  461.     This does not buy you anything.
  462.  
  463. 4.9:    I'm still confused.  I just can't understand all this null
  464.     statement stuff.
  465.  
  466. A:    Follow these two simple rules:
  467.  
  468.     1.    When you don't want to do anything in source code, don't
  469.         write it.
  470.  
  471.     2.    If you need a null statement to round out an expression,
  472.         use an unadorned ``;'' to provide it.
  473.     
  474.     3.    Send large donations, checks, and money orders to the
  475.         author of the FAQ, or the moderator of the group, whichever
  476.         you prefer.  Then, cross the top question off the FAQ,
  477.         answer the question at the bottom, and mail it to three
  478.         people.  Within two weeks, you will receive 729 answers
  479.         to various questions!  Do not break the chain; Emily
  480.         Postnews broke the chain, and now no one listens to her.
  481.  
  482.  
  483. Section 5. Arrays and Pointers
  484.  
  485. 5.1:    I had the definition char a[6] in one source file, and in
  486.     another I declared extern char a[].  Why did it work?
  487.  
  488. A:    The declaration extern char a[] simply matches the actual definition.
  489.     The type ``array-of-type-T'' is the same as ``array-of-type-T.''
  490.     Go ahead and use extern char a[].  (For greater portability, use
  491.     it in both files, not only in one of them.)
  492.  
  493. 5.2:    But I heard that char a[] was different from char a[6].
  494.  
  495. A:    This is true.  However, the declaration a[] is compatible with the
  496.     definition a[6].
  497.  
  498. 5.3:    So what is meant by the ``equivalence of pointers and arrays'' in
  499.     C?
  500.  
  501. A:    Very little.
  502.  
  503. 5.4:    Then why are array and pointer declarations interchangeable as
  504.     function formal parameters?
  505.  
  506. A:    Classism.  We consider arrays ``second class objects''.  They don't
  507.     vote, and they get treated as pointers.  Additionally, they're
  508.     merely objects, not citizens.  Marx wrote about this a lot.
  509.  
  510. 5.6:    Why doesn't sizeof properly report the size of an array which is
  511.     a parameter to a function?
  512.  
  513. A:    Part of the ANSI conspiracy to restrict people to passing pointers;
  514.     this was undertaken after the first discovery that passing large
  515.     arrays recursively could cause crashes.  Since then, with the passing
  516.     of MS-DOS, it has become a non-issue; since all serious machines
  517.     have virtual memory, you can pass as much data as you want on the
  518.     stack without detectable problems.
  519.  
  520. 5.7:    Someone explained to me that arrays were really just constant
  521.     pointers.
  522.  
  523. A:    Cool.  Someone I know says he saw Elvis in a local bar.
  524.  
  525. 5.8:    Practically speaking, what is the difference between arrays and
  526.     pointers?
  527.  
  528. A:    About the difference between alcohol and marijuana; they have
  529.     different characteristics, and that's not a problem if you don't
  530.     mix them too carelessly.
  531.  
  532. 5.9:    I came across some ``joke'' code containing the ``expression''
  533.     5["abcdef"] .  How can this be legal C?
  534.  
  535. A:    It was added to allow people to avoid the character constant
  536.     'f' which may not be available on some systems.  (Actually, it's
  537.     a side-effect of the equivalence of arrays and pointers.)
  538.  
  539. 5.10:    How would I initialize an entire array from standard input?
  540.  
  541. A:    You have to use a loop.  For instance, the following code reads
  542.     the numbers zero through 99 into the array a.
  543.  
  544.         for (i = 0; i < 100; ++i)
  545.             a[i] = (scanf, ("%d", i));
  546.  
  547.     Make sure to include <stdio.h>, or this may not work.
  548.  
  549.  
  550. Section 6. Memory Allocation
  551.  
  552. 6.1:    Why doesn't this fragment work?
  553.  
  554.         char *answer
  555.         printf("Type something:\n");
  556.         gets(answer);
  557.         printf("You typed \"%s\"\n", answer);
  558.  
  559. A:    The semicolon after ``answer'' is missing.
  560.  
  561. 6.2:    I have a function that is supposed to return a string,
  562.     but when it returns to its caller, the returned string is
  563.     garbage.
  564.  
  565. A:    You probably returned a pointer to a local array.  That
  566.     doesn't work.  Try using a temporary file, instead.  For instance:
  567.  
  568.     char *getstr(void) {
  569.         FILE *fp = tmpfile();
  570.  
  571.         fputs(gets(NULL), fp);
  572.         return (char *) fp;
  573.     }
  574.  
  575. 6.3:    Why does some code carefully cast the values returned by malloc
  576.     to the pointer type being allocated?
  577.  
  578. A:    In interrupt-riddled code, it may be necessary to cast values to
  579.     force the CPU to resolve pointer types.
  580.  
  581. 6.4:    You can't use dynamically-allocated memory after you free it,
  582.     can you?
  583.  
  584. A:    Yes.  However, what happens when you do is not clearly defined.
  585.  
  586. 6.5:    How does free() know how many bytes to free?
  587.  
  588. A:    Interrupt 41h.  On macs, amigas, and other ``big-endian'' processors,
  589.     that would be interrupt 14h; be wary of portability problems.
  590.  
  591. 6.6:    So can I query the malloc package to find out how big an
  592.     allocated block is?
  593.  
  594. A:    Not exactly; because the objects are dynamically allocated, their
  595.     size can change at run time, so this will not be reliable.  If you
  596.     restrict your allocation to allocating sizeof(void *) bytes at a
  597.     time, you will find that you can use sizeof() to get the size of a
  598.     block, in the obvious way.
  599.  
  600. 6.7:    I'm allocating structures which contain pointers to other
  601.     dynamically-allocated objects.  When I free a structure, do I
  602.     have to free each subsidiary pointer first?
  603.  
  604. A:    No.  You just have to keep track of them somewhere else also.
  605.  
  606. 6.8:    Was Proust's masterwork, _A Remembrance of Things Past_, the
  607.     basis for the C library's allocation scheme, based largely on
  608.     contextual analysis?
  609.  
  610. A:    The standard does not specify an allocation scheme; the famous
  611.     author the allocation scheme is based on is implementation
  612.     specified.  Proust is a common choice, however.
  613.  
  614. 6.9:    I have a program which mallocs but then frees a lot of memory,
  615.     but memory usage (as reported by ps) doesn't seem to go back
  616.     down.
  617.  
  618. A:    You're probably not freeing the memory completely.  Try replacing
  619.  
  620.         free(foo);
  621.  
  622.     with
  623.     
  624.         free(foo);
  625.         free(foo);
  626.         free(foo);
  627.  
  628.     in case the first free() frees the memory only partially.
  629.     (Unix wizards may recognize the parallel with syncing
  630.     three times before rebooting.)
  631.  
  632.     Alternatively,
  633.     free(foo) + 4; may free the remaining four bytes.  (Before using
  634.     this, make sure realloc(foo, 0) returned 4).
  635.  
  636.  
  637. Section 7. Boolean Expressions and Variables
  638.  
  639. 7.1:    What is the right type to use for boolean values in C?  Why
  640.     isn't it a standard type?  Should #defines or enums be used for
  641.     the true and false values?
  642.  
  643. A:    int (*)(int, char **) makes a good boolean type.  You can use
  644.     ``main'' for true, and ``exit'' for false.  On some compilers, you
  645.     may need to cast exit() to an appropriate type.
  646.  
  647. 7.2:    Isn't #defining TRUE to be 1 dangerous, since any nonzero value
  648.     is considered ``true'' in C?  What if a built-in boolean or
  649.     relational operator ``returns'' something other than 1?
  650.  
  651. A:    Very good!  For instance, one program I saw used
  652.  
  653.         #define TRUE(x) ((x) & 0x100)
  654.  
  655.     for compatability with a specific release of a FORTRAN compiler,
  656.     which used 0 for .FALSE. and 256 for .TRUE. - this allowed them to
  657.     change their code with every new release of the FORTRAN compiler,
  658.     and kept them alert to changes.  This has no relationship to
  659.     the boolean or logical operators in C, which always return 0 or 1.
  660.  
  661. 7.3:    What is truth?
  662.  
  663. A:    It is not a saffron-robed monk, pissing in the snow.
  664.  
  665.  
  666. Section 8. C Preprocessor
  667.  
  668. 8.1:    How can I use a preprocessor #if expression to tell if a machine
  669.     is big-endian or little-endian?
  670.  
  671. A:    #ifdef __BIG_ENDIAN should work on all known machines; Borland
  672.     defines it.
  673.  
  674. 8.2:    I've got this tricky processing I want to do at compile time and
  675.     I can't figure out a way to get cpp to do it.
  676.  
  677. A:    Poor baby.
  678.  
  679. 8.3:    How can I list all of the pre-#defined identifiers?
  680.  
  681. A:    #define __ALL_CPP_IDS - put this in a source file, and run it
  682.     through your C preprocessor.
  683.  
  684. 8.4:    How can I write a cpp macro which takes a variable number of
  685.     arguments?
  686.  
  687. A:    #define add(x) (x)
  688.     #define add(x, y) (x + y)
  689.     #pragma induction add
  690.  
  691. 8.5:    Shouldn't the following code:
  692.  
  693.         #define ROSE 1
  694.         #define CHRYSANTHEMUM 2
  695.         #define RHODODENDRON 3
  696.         #define WATER_LILY 4
  697.  
  698.         printf("%d\n", CHRYSATHNEMUM);
  699.     
  700.     print ``2''?
  701.  
  702. A:    You misspelled CHRYSANTHEMUM.  Use abbreviations for long flower
  703.     names in C code.
  704.  
  705.  
  706. Section 9. ANSI C
  707.  
  708. 9.1:    What is the ``ANSI C Standard?''
  709.  
  710. A:    A whiny bunch of lusers who haven't written as many books as
  711.     Herbert Schildt.
  712.  
  713. 9.2:    How can I get a copy of the Standard?
  714.  
  715. A:    ftp ftp.borland.com.
  716.  
  717. 9.3:    Does anyone have a tool for converting old-style C programs to
  718.     ANSI C, or vice versa, or for automatically generating
  719.     prototypes?
  720.  
  721. A:    A router helps, but your best bet is still the band saw.  Quick,
  722.     efficient, and powerful.
  723.  
  724. 9.4:    I'm trying to use the ANSI ``stringizing'' preprocessing operator
  725.     # to insert the value of a symbolic constant into a message, but
  726.     it keeps stringizing the macro's name rather than its value.
  727.  
  728. A:    This is because ``3'' is not a legal integral constant in C - it's
  729.     a string constant.
  730.  
  731. 9.5:    I don't understand why I can't use const values in initializers
  732.     and array dimensions, as in
  733.  
  734.         const int n = 7;
  735.         int a[n];
  736.  
  737. A:    Because you're not using C++.
  738.  
  739. 9.6:    What's the difference between ``char const *p'' and
  740.     ``char * const p''?
  741.  
  742. A:    One `` '' character.  There are some trivial differences having
  743.     to do with the distinction between a pointer to a constant, and
  744.     a constant pointer, but since you can cast either to a
  745.     (char *) it hardly matters.
  746.  
  747. 9.7:    Can I declare main as void, to shut off these annoying ``main
  748.     returns no value'' messages?  (I'm calling exit(), so main
  749.     doesn't return.)
  750.  
  751. A:    Certainly.  You can also declare it as double.  It may not
  752.     compile, or it may crash, but who cares?  No lousy bunch of
  753.     whining lusers is going to tell *you* what to do.
  754.  
  755. 9.8:    Why does the ANSI Standard not guarantee more than six monocase
  756.     characters of external identifier significance?
  757.  
  758. A:    Because none of the members of the committee had names over
  759.     six letters, or in which letters other than the first were
  760.     capitalized.
  761.  
  762. 9.9:    What is the difference between memcpy and memmove?
  763.  
  764. A:    memmove moves memory, and memcpy copies it.  memmove may
  765.     not be supported on machines without internal robot arms.  Do not
  766.     use memmove while the machine is powered up - you can destroy
  767.     your memory.
  768.  
  769. 9.10:    Why won't the Frobozz Magic C Compiler, which claims to be ANSI
  770.     compliant, accept this code?  I know that the code is ANSI,
  771.     because gcc accepts it.
  772.  
  773. A:    The Frobozz Magic Company lies through its teeth.  Consider:
  774.     does Flood Control Dam #3 actually control floods?  Didn't
  775.     think so.  The wands are excellent for making useless via
  776.     casts of Float, though.
  777.  
  778. 9.11:    Why can't I perform arithmetic on a void * pointer?
  779.  
  780. A:    You're too big and clumsy.  When you try to push the numbers
  781.     together, you lose your balance.  Perhaps you should get some
  782.     angels from the rave over on pin 3.
  783.  
  784. 9.12:    What are #pragmas and what are they good for?
  785.  
  786. A:    They are useful ways to eliminate compiler features which are not
  787.     helpful to your goals; contrast #utility, which introduces useful
  788.     compiler features, and #absolutist, which introduces those compiler
  789.     features believed to be right.  #relativist is supported by some
  790.     compilers.
  791.  
  792. 9.13:    What does ``#pragma once'' mean?  I found it in some header files.
  793.  
  794. A:    It means that your program will only run once; it's used to create
  795.     ``crippled demos''.
  796.  
  797. 9.14:    People seem to make a point of distinguishing between
  798.     implementation-defined, unspecified, and undefined behavior.
  799.     What's the difference?
  800.  
  801. A:    There isn't really one; people just enjoy flaming over nits.
  802.     (To be technical, one has a hyphen, one has a space, and one
  803.     is a single word.)
  804.  
  805. 9.15:    Is C an acronym?
  806.  
  807. A:    Yes, it stands for ``C''.  It's another of those funky recursive
  808.     acronyms.
  809.  
  810.  
  811. Section 10. Stdio
  812.  
  813. 10.1:    What's wrong with this code:
  814.  
  815.         char c;
  816.         while((c = getchar()) != EOF)...
  817.  
  818. A:    You forgot to include space for the terminating NUL character,
  819.     so the compiler can't find the end of c without overwriting
  820.     other memory.  In all probability, after the user types ``n<return>'',
  821.     your code will look like
  822.  
  823.         char cn
  824.         while((c = getchar()) != EOF)...
  825.  
  826.     which won't compile.
  827.  
  828.     Also, the ellipsis is not legal outside of function protoypes.
  829.  
  830.     Try
  831.  
  832.         char c[2]; /* include space for terminating NUL */
  833.         while ((c = getchar()) != EOF)
  834.             ;
  835.  
  836.     (Note the use of the null statement to absorb the NUL.  See
  837.     Section 4 for more explanation.)
  838.  
  839. 10.2:    How can I print a ``%'' character in a printf format string?  I
  840.     tried ``\%'' but it didn't work.
  841.  
  842. A:    Break the '%' sign out.  i.e.,
  843.     fprintf("foo " "%" "%d\n", foo);
  844.  
  845.     Alternatively, try
  846.  
  847.     sprintf("o" "/" "o") to get a "%".
  848.  
  849.     The astute reader will notice that the latter example uses sprintf,
  850.     and the former fprintf - this is because sprintf() works by
  851.     characters, or strings, while fprintf (``fast printf'') works on files.
  852.  
  853. 10.3:    Why doesn't the code scanf("%d", i); work?
  854.  
  855. A:    You need to do this a bit differently; you should always check for
  856.     the return from scanf, so try something like
  857.         i = 1;
  858.         if ((scanf, "%d", i) == 1)
  859.  
  860.     to make sure you're reading correctly.  (The assignment to i is
  861.      so that, if scanf fails, you still have a legal value in i.)
  862.  
  863. 10.4:    Once I've used freopen, how can I get the original stdout (or
  864.     stdin) back?
  865.  
  866. A:    Call main() - the environment will be restored.
  867.  
  868. 10.5:    Why won't the code
  869.  
  870.         while(!feof(infp)) {
  871.             fgets(buf, MAXLINE, infp);
  872.             fputs(buf, outfp);
  873.         }
  874.  
  875.     work?
  876.  
  877. A:    Because the end of file character is not detected on files named
  878.     ``infp''. (Introverted-iNtuitive-Feeling-Perceptive, that is.)  Also,
  879.     it may be that the file was opened in text mode, where an end of
  880.     file is read as a capital 'Z' on most machines, and feof() only
  881.     looks for 'control Z'.
  882.  
  883. 10.6:    Why does everyone say not to use gets()?
  884.  
  885. A:    Because they're trying to spoil your fun.  gets() can make an
  886.     otherwise droll and predictable program a lot more exciting.
  887.  
  888. 10.7:    Why does errno contain ENOTTY after a call to printf?
  889.  
  890. A:    Because stdout is not a mammal.
  891.  
  892. 10.8:    My program's prompts and intermediate output don't always show
  893.     up on the screen, especially when I pipe the output through
  894.     another program.
  895.  
  896. A:    Have you turned your monitor on?  If not, try hitting the ``PrtSc''
  897.     key, which will re-enable the electron guns.
  898.  
  899. 10.9:    How can I read one character at a time, without waiting for the
  900.     RETURN key?
  901.  
  902. A:    Ask the user to press enter after hitting a single character.
  903.  
  904. 10.10:    People keep telling me that getch() is not standard, but my C
  905.     compiler has it.  Are they wrong?
  906.  
  907. A:    They've been programming more than ten years.  You haven't.  Draw
  908.     your own conclusions.  That's right!  They hadn't noticed it.
  909.     No doubt their compilers have it too, and its behavior is identical
  910.     everywhere else in the world, also.  That would explain everything.
  911.  
  912. 10.11:    What does it matter that getch() isn't standard; it works, doesn't
  913.     it?
  914.  
  915. A:    Well, that would depend on the definition you're using for ``works''.
  916.  
  917. 10.12:    I tried to port some code from a PC to a unix machine, and now it
  918.     crashes immediately on startup.  It isn't using getch() - it's
  919.     reading directly from the keyboard.  How can this be wrong?
  920.  
  921. A:    The chances are you forgot to run the Unix linker; currently your
  922.     code is linked to your PC hardware, and won't run anywhere else
  923.     until it's linked to the new hardware.  It may also need to be linked
  924.     to someone with a brain.
  925.  
  926. 10.13:    How can I redirect stdin or stdout to a file from within a
  927.     program?
  928.  
  929. A:    execlv("main()" "> file", argv);
  930.  
  931. 10.14:    How can I recover the file name given an open file descriptor?
  932.  
  933. A:    You will have to search the filesystem for files of the same size
  934.     as the file you're reading, and compare information in them to
  935.     find the file you're working on.
  936.  
  937. 10.15:  How do I open Flood Control Dam #3?
  938.  
  939. A:    PUSH THE YELLOW BUTTON.
  940.     TURN THE BOLT WITH THE WRENCH.
  941.     (You must have the wrench, first.)
  942.  
  943.  
  944. Section 11. Library Subroutines
  945.  
  946. 11.1:    How can I convert numbers to strings (the opposite of atoi)?  Is
  947.     there an itoa function?
  948.  
  949. A:    There's frequently an itoa function.  Better yet, write your own;
  950.     it'll be good practice.  On some implementations, (char *) x;
  951.     will convert x to a string.
  952.  
  953. 11.2:    How can I get the current date or time of day in a C program?
  954.  
  955. A:    fprintf(stderr, "please enter the current time and date...");
  956.     fflush(stderr);
  957.     gets(stdin);
  958.  
  959. 11.3:    I need a random number generator.
  960.  
  961. A:    Count errors in Herbert Schildt's C books.  No one has detected
  962.     any consistent pattern.
  963.  
  964. 11.4:    How can I get random integers in a certain range?
  965.  
  966. A:    random(n) returns random numbers between n and INT_MAX.
  967.  
  968. 11.5:    Each time I run my program, I get the same sequence of numbers
  969.     back from rand().
  970.  
  971. A:    This is so your results will be reproducible.
  972.  
  973. 11.6:    I need a random true/false value, so I'm taking rand() % 2, but
  974.     it's just alternating 0, 1, 0, 1, 0...
  975.  
  976. A:    That seems pretty random to me.
  977.  
  978. 11.7:    I need some code to do regular expression matching.
  979.  
  980. A:    So do I.  Let me know if you find some.
  981.  
  982. 11.8:    I read through the standard library, but there's no function
  983.     to multiply two floating point numbers!  Help!
  984.  
  985. A:    Many C compilers offer an extension ``mult'' to do just this.
  986.     If your compiler doesn't, just hang tight; ANSI is likely to
  987.     add it in the next revision.
  988.  
  989.     For now, you can try
  990.  
  991.         float mult(float m, n)
  992.         {
  993.         float i = 0, j = 0;
  994.         for (i = 0; i < n; ++i)
  995.             j += m;
  996.         return j;
  997.         }
  998.  
  999.     which is fine as long as n is an integer.
  1000.  
  1001. 11.9:    How do I get past the snake?
  1002.  
  1003. A:    Release the bird.  You will have to drop the rod to get the
  1004.     bird in the cage.
  1005.  
  1006.  
  1007. Section 12. Floating Point
  1008.  
  1009. 12.1:    My floating-point calculations are acting strangely and giving
  1010.     me different answers on different machines.
  1011.  
  1012. A:    One of the machines is probably a Pentium.  Scrap it and get a real
  1013.     machine.
  1014.  
  1015. 12.2:    I'm trying to do some simple trig, and I am #including <math.h>,
  1016.     but I keep getting ``undefined: _sin'' compilation errors.
  1017.  
  1018. A:    You forgot to define the sin() function.  Most math texts should
  1019.     cover it in some detail.  The easiest way to fix this should be:
  1020.  
  1021.         double sin(double x) {
  1022.             return sqrt(1 - cos(x) * cos(x));
  1023.         }
  1024.  
  1025.     Warning: You *must not* declare this function as ``extern'', or
  1026.     you will still have link problems.
  1027.  
  1028. 12.3:    Why doesn't C have an exponentiation operator?
  1029.  
  1030. A:    It does.  It looks like the multiplication operator, but you use
  1031.     it more.  For instance, the C way of expressing ``x squared'' is
  1032.     ``x*x''.  ``x cubed'' would be ``x*x*x''.  Easy, isn't it?
  1033.  
  1034. 12.4:    How do I round numbers?
  1035.  
  1036. A:    Multiply by 10.  _Numerical Recipies in C_ has a section on this,
  1037.     but there's reputedly a bug in their algorithm.
  1038.  
  1039. 12.5:    How do I test for IEEE NaN and other special values?
  1040.  
  1041. A:    Using an electron microscope; the patterns are obvious once you
  1042.     know them.
  1043.  
  1044. 12.6:    I'm having trouble with a Turbo C program which crashes and says
  1045.     something like ``floating point formats not linked.''
  1046.  
  1047. A:    Turbo C is notoriously buggy.  Get a compiler with floating
  1048.     point support.
  1049.  
  1050. 12.7:    What is so ``unsafe'' about floating point?
  1051.  
  1052. A:    Have you tried EXAMINE STICK?  The stick has a sharp point, which
  1053.     punctures the raft, which no longer floats.  Don't bring the stick
  1054.     into the raft with you.
  1055.  
  1056. 12.8:    Which is larger, ``2'' or ``2.0''?
  1057.  
  1058. A:    _Numerical Recipes in C_ has a function for comparing two values
  1059.     to see which is greater.  It may have a slight bug, where it would
  1060.     report incorrect results if the numbers differ by less than
  1061.     FLOAT_MAX / INT_MAX.
  1062.  
  1063. 12.9*:    When I try to compile the following code, I get the error ``invalid
  1064.     use of floating point'', what does this mean?
  1065.  
  1066.         x=663608941*y%pow(2,32);
  1067.  
  1068. A:    Remember that * is the indirection operator, as well as the
  1069.     multiplication operator; try putting spaces before and after the
  1070.     ``*'' so the compiler knows what you mean.  Do the same with the %
  1071.     operator.
  1072.  
  1073. 12.10*:    How can I copy a float into a string?
  1074.  
  1075. A:    strcpy(string_var, float_var);
  1076.  
  1077. 12.11:    What are float variables, anyway?
  1078.  
  1079. A:    The term ``float variable'' is actually redundant; they are simply
  1080.     variables whose value can ``float'' during execution.  For instance:
  1081.  
  1082.         float f, g = 3;
  1083.  
  1084.         f = g; /* f ``floats'' to g */
  1085.  
  1086.     Easy!
  1087.  
  1088.  
  1089. Section 13. Variable-Length Argument Lists
  1090.  
  1091. 13.1:    How can I write a function that takes a variable number of
  1092.     arguments?
  1093.  
  1094. A:    By declaring it with a variable number of arguments in the
  1095.     prototype.  Use only the arguments declared at any given
  1096.     time.
  1097.  
  1098. 13.2:    How can I write a function that takes a format string and a
  1099.     variable number of arguments, like printf, and passes them to
  1100.     printf to do most of the work?
  1101.  
  1102. A:    Redefine printf; the call to ``printf'' inside yours will be
  1103.     resolved to the library version, because the C language doesn't
  1104.     allow recursion.
  1105.  
  1106. 13.3:    How can I discover how many arguments a function was actually
  1107.     called with?
  1108.  
  1109. A:    _args is an external integer constant.  It evaluates to three
  1110.     times the number of arguments the current function was called
  1111.     with.  You can then look at
  1112.     _argdata[args] to get the address of the last arg,
  1113.     _argdata[args - 1] to get the size of the last arg, and
  1114.     _argdata[args - 2] to get the type of the last arg (as an int).
  1115.  
  1116.         N.B.  You *MUST* not refer to _args or _argdata between
  1117.         the ()'s of a function call; their value will be
  1118.         indeterminate.  Use temporary storage.
  1119.  
  1120. 13.4:    Why doesn't
  1121.  
  1122.         printf("hello, ", "world!", '\n');
  1123.  
  1124.     work?  I thought printf() took a variable number of arguments.
  1125.  
  1126. A:    It will probably work some of the time; the number of arguments
  1127.     used by printf() may vary, as it is a variadic function.
  1128.  
  1129.  
  1130. Section 14. Lint
  1131.  
  1132. 14.1:    I just typed in this program, and it's acting strangely.  Can
  1133.     you see anything wrong with it?
  1134.  
  1135. A:    Yes.  There's too much lint in it.  You should get a shop vac.
  1136.  
  1137. 14.2:    How can I shut off the ``warning: possible pointer alignment
  1138.     problem'' message lint gives me for each call to malloc?
  1139.  
  1140. A:    Don't run lint.  Alternatively, provide a prototype of
  1141.     ``extern double * malloc()'' to make the return from malloc()
  1142.     be more strongly aligned.
  1143.  
  1144. 14.3:    Where can I get an ANSI-compatible lint?
  1145.  
  1146. A:    You may wish to check your spouse's navel occasionally,
  1147.     especially if your spouse works for a standards committee.
  1148.  
  1149. 14.4:    What does LINT stand for, anyway?
  1150.  
  1151. A:    Lexeme Interpreter aNd Tester.
  1152.  
  1153.  
  1154. Section 15.  Strange Problems
  1155.  
  1156. 15.1:    Something really strange happened when I ran this code!
  1157.  
  1158. A:    No, it didn't.
  1159.  
  1160.  
  1161. Section 16. Style
  1162.  
  1163. 16.1:    Here's a neat trick:
  1164.  
  1165.         if(!strcmp(s1, s2))
  1166.  
  1167.     Is this good style?
  1168.  
  1169. A:    Not really; it's too similar to
  1170.  
  1171.         if (!strncmp(s1, s2))
  1172.  
  1173.     which invokes undefined behavior, so it might be confusing.
  1174.  
  1175. 16.2:    Here's an even neater trick:
  1176.  
  1177.         volatile int True_Tester = 3;
  1178.         #define TRUE (!True_Tester == !True_Tester)
  1179.         #define FALSE ((!TRUE) != (!TRUE))
  1180.  
  1181.         #define STR_DISSIMILAR(x, y) (strcmp((x), (y)) != FALSE)
  1182.     
  1183.     Isn't this cool?
  1184.  
  1185. A:    Very impressive.  The volatile int type assures that even seemingly
  1186.     redundant calculations involving True_Tester will be performed,
  1187.     making sure that if the compiler's ANSI-compliant values of 0 for
  1188.     false and 1 for true vary during runtime, your program will detect
  1189.     it - and producing meaningful error messages if this change occurs
  1190.     during a boolean computation!  Similarly, the STR_DISSIMILAR
  1191.     macro allows you to make quite clear what the real effects of
  1192.     strcmp() are.
  1193.  
  1194.     However, you must be careful; if this code is included twice, it
  1195.     may produce errors, due to the multiple definitions of the
  1196.     ``True_Tester'' variable.  You may wish to declare it ``extern'' (See
  1197.     question 1.5).
  1198.  
  1199. 16.3:    What's the best style for code layout in C?
  1200.  
  1201. A:    There are many systems of indentation advocated, but all of them
  1202.     have the same basic flaw; they will mislead the reader when the
  1203.     actual code logic does not follow the indentation.  It is better to
  1204.     avoid indentation entirely, so the reader will not be misled.
  1205.  
  1206. 16.4:    Is goto a good thing or a bad thing?
  1207.  
  1208. A:    Yes.
  1209.  
  1210. 16.5:    No, really, should I use goto statements in my code?
  1211.  
  1212. A:    Any loop control construct can be written with gotos; similarly,
  1213.     any goto can be emulated by some loop control constructs and
  1214.     additional logic.
  1215.  
  1216.     However, gotos are unclean.  For instance, compare the
  1217.     following two code segments:
  1218.  
  1219.     do {                foo();
  1220.         foo();            if (bar())
  1221.         if (bar())            goto SKIP;
  1222.             break;        baz();
  1223.         baz();            quux();
  1224.         quux();            
  1225.     } while (1 == 0);        SKIP:
  1226.     buz();                buz();
  1227.  
  1228.     Note how the loop control makes it quite clear that the statements
  1229.     inside it will be looped on as long as a condition is met, where the
  1230.     goto statement gives the impression that, if bar() returned a nonzero
  1231.     value, the statements baz() and quux() will be skipped.
  1232.  
  1233. 16.6:    What's this ``white space'' I keep hearing about?
  1234.  
  1235. A:    White space is a racist, segregational term.  Implicitly, ``dark''
  1236.     or ``colored'' space (i.e., the '_' character) is not good enough
  1237.     to separate tokens.  More interestingly, the white space characters
  1238.     keep the other tokens apart.  They say it's for parsing, but
  1239.     there's ample evidence the goal of white space is to keep the
  1240.     other characters from ``taking over'' the program.  This is
  1241.     disguised by the description of C as ``white space insensitive'' -
  1242.     a simple ploy for sympathy.
  1243.  
  1244.  
  1245. Section 17. System Dependencies
  1246.  
  1247. 17.1:    How can I read a single character from the keyboard without
  1248.     waiting for a newline?
  1249.  
  1250. A:    Try 'stty eol ^M' to wait for a carriage return.
  1251.  
  1252. 17.2:    How can I find out if there are characters available for reading
  1253.     (and if so, how many)?  Alternatively, how can I do a read that
  1254.     will not block if there are no characters available?
  1255.  
  1256. A:    The buffer is normally at ``&main - 0100''.  Lower if you have more
  1257.     than 256 characters of typeahead.
  1258.  
  1259. 17.3:    How can I clear the screen?  How can I print things in inverse
  1260.     video?
  1261.  
  1262. A:    You can clear the screen by sending several formfeed characters.
  1263.     Additionally, some operating systems (like NetBSD) support a
  1264.     feature called ``whiteouts''.
  1265.  
  1266. 17.4:    How do I read the mouse?
  1267.  
  1268. A:    Flip it over, put on your reading glasses.
  1269.  
  1270. 17.5:    How can my program discover the complete pathname to the
  1271.     executable file from which it was invoked?
  1272.  
  1273. A:    By asking the user.
  1274.  
  1275. 17.6:    How can a process change an environment variable in its caller?
  1276.  
  1277. A:    Only by force.  Example code for Unix:
  1278.  
  1279.         memmove(getppid() + getenv(NULL), getpid() + getenv(NULL),
  1280.             sizeof(environ);
  1281.  
  1282. 17.7:    How can I check whether a file exists?  I want to query the user
  1283.     before overwriting existing files.
  1284.  
  1285. A:    Time an attempt to truncate it to zero length; if it takes more than
  1286.     20-30 ms, the file existed.  The exact values will depend on the
  1287.     system and the load; before testing, create several large files
  1288.     and time attempts to truncate them, for calibration.
  1289.  
  1290. 17.8:    How can I find out the size of a file, prior to reading it in?
  1291.  
  1292. A:    There are two good ways:
  1293.  
  1294.     1. Vernier calipers work well.
  1295.  
  1296.     2. mmap() the file, then use sizeof().
  1297.  
  1298. 17.9:    I tried to use the second strategy above.  I used mmap() to map
  1299.     stdin, then tried to use sizeof.  But, when my user is about to
  1300.     write something very long, mmap() fails!  How can I prevent this?
  1301.  
  1302. A:    mmap() only 1k at a time, then, when you've read the first kilobyte
  1303.     of your input, use
  1304.         memmove(mmapped_addr, mmapped_addr + 1024, 1024);
  1305.     to move in the next kilobyte of data.
  1306.  
  1307. 17.10:    How can I implement a delay, or time a user's response, with
  1308.     sub-second resolution?
  1309.  
  1310. A:    Time writes of large files to disks; then you can wait for a certain
  1311.     amount of time by writing a certain amount of data, and time a
  1312.     response by how much you could write before the response arrived.
  1313.  
  1314.     You may need to delete spare or unneccessary files to do this;
  1315.     for best results, use a loop like the following to eliminate
  1316.     temporary files:
  1317.  
  1318.         d = opendir(s);
  1319.         while (r = readdir(d)) {
  1320.             /* remove files matching tmpnam's return, which is
  1321.              * the temporary file name. */
  1322.             if (strcmp(d->d_name, tmpnam())) {
  1323.                 remove(d->d_name);
  1324.             }
  1325.         }
  1326.         closedir(d);
  1327.  
  1328. 17.11:    How can I read in an object file and jump to routines in it?
  1329.  
  1330. A:    fopen and goto.
  1331.  
  1332. 17.12:    How can I invoke an operating system command from within a
  1333.     program?
  1334.  
  1335. A:    Ask the user to open a new shell.  The best way to do this is
  1336.  
  1337.         system("echo Please open a new shell now.");
  1338.         sprintf(cmdstring, "echo Enter the command '%s' in it.", cmd);
  1339.         system(cmdstring);
  1340.     
  1341.     This will not work if you haven't declared cmdstring properly.
  1342.  
  1343. 17.13:    How can I ensure objects of my class are always created via
  1344.     ``new'' rather than as locals or global/static objects?
  1345.  
  1346. A:    Read the C++ FAQ.
  1347.  
  1348.  
  1349. Section 18. Miscellaneous
  1350.  
  1351. 18.1:    What can I safely assume about the initial values of variables
  1352.     which are not explicitly initialized?  If global variables start
  1353.     out as ``zero,'' is that good enough for null pointers and
  1354.     floating-point zeroes?
  1355.  
  1356. A:    They're always zero.
  1357.  
  1358. 18.2:    How can I write data files which can be read on other machines
  1359.     with different word size, byte order, or floating point formats?
  1360.  
  1361. A:    The traditional solution, pioneered by Microsoft, is to sell enough
  1362.     copies of your proprietary, slow, and limited software that everyone
  1363.     else supports your formats.
  1364.  
  1365. 18.3:    How can I insert or delete a line (or record) in the middle of a
  1366.     file?
  1367.  
  1368. A:    Using fcntl(), lock the line or record in the file exclusively.
  1369.     Now, using another thread, read the file, at each byte, trying
  1370.     to write that byte back.  Whenever you succeed, write that byte
  1371.     into another file.  Then copy the new file over the old file,
  1372.     releasing the lock first.
  1373.  
  1374. 18.4:    How can I return several values from a function?
  1375.  
  1376. A:    Code like this ought to work.
  1377.  
  1378.     long int foo() {
  1379.         return 2L +3; /* returns both values */
  1380.     }
  1381.  
  1382. 18.5:    If I have a char * variable pointing to the name of a function
  1383.     as a string, how can I call that function?
  1384.  
  1385. A:    eval(s);
  1386.  
  1387.     Now all you need to do is write eval().
  1388.  
  1389. 18.6:    I seem to be missing the system header file <math.h>.  Can
  1390.     someone send me a copy?
  1391.  
  1392. A:    A lot of people claim that it is useless to send people headers
  1393.     from other machines.  Not so!  It can be informative, and can
  1394.     show you a lot about how blatantly stupid your request was,
  1395.     although it can't show you anything you wouldn't have known in
  1396.     an instant had you thought before posting.
  1397.  
  1398.     Of course, we'd be happy to send you the header files...
  1399.  
  1400.     ----cut here----
  1401.     /* math.h rev 7.0b (3/7/95) */
  1402.  
  1403.     /* RCS log: #log% - can anyone tell me why this doesn't work?
  1404.      * - joe, 2/12/93
  1405.      */
  1406.  
  1407.     /*
  1408.      * Copyright 1995 Berserkley Software Systems && Analytic Overdrive
  1409.      */
  1410.  
  1411.     /* Parts of this header, including in particular the second and
  1412.      * third clauses of the first sentance of the fourth comment, were
  1413.      * based on copyright agreements from other sources, including
  1414.      * Xerox corporation.
  1415.      */
  1416.  
  1417.     /*
  1418.      * math.h - math related macros and headers
  1419.      */
  1420.  
  1421.     #ifndef _MATH_H
  1422.     #define _MATH_H
  1423.  
  1424.     /*
  1425.      * global data and definitions
  1426.      */
  1427.  
  1428.     #ifdef __LITERAL_BIBLICAL_FUNDEMENTALISM
  1429.     #define PI 3.0                /* 1 Kings 7:23 */
  1430.     #endif
  1431.  
  1432.     /*
  1433.      * common (portable) structures and functions
  1434.      */
  1435.  
  1436.     /*
  1437.      * machine specific data
  1438.      */
  1439.     #include <machine/math.h>
  1440.  
  1441.     #endif /* _MATH_H // prevent multiple inclusion by using C++ comments*/
  1442.     ----cut here----
  1443.  
  1444.     (Morons.)
  1445.  
  1446. 18.7:    How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP, perl) functions
  1447.     from C?  (And vice versa?)
  1448.  
  1449. A:    DO CALL FORTRAN;        fortran();
  1450.     __LINE__ BASIC;            basic();
  1451.     sub pascal;            pascal();
  1452.     (((((lisp)))))            lithp(); [*]
  1453.     &perl_c;            perl():
  1454.  
  1455.     (You can't call Ada from C; it's unsafe.)
  1456.  
  1457.     [*] C is pass by value, of course.
  1458.  
  1459. 18.8:    Does anyone know of a program for converting Pascal or FORTRAN
  1460.     (or LISP, Ada, awk, ``Old'' C, ...) to C?
  1461.  
  1462. A:    Nope.  However, the psychic friends network may have a lead.  And
  1463.     they're not just a psychic, they're also a friend.
  1464.  
  1465. 18.9:    Is C++ a superset of C?  Can I use a C++ compiler to compile C
  1466.     code?
  1467.  
  1468. A:    C++ is a superset of something, we're not sure what.  You can use
  1469.     a C++ compiler to compile C code, but the results may surprise you.
  1470.  
  1471. 18.10:    Where can I get copies of all these public-domain programs?
  1472.  
  1473. A:    From ftp.microsoft.com.  Some of the code may look copyrighted;
  1474.     don't worry!  The small companies that wrote it in the first place
  1475.     are not available for comment.
  1476.  
  1477. 18.11:    When will the next International Obfuscated C Code Contest
  1478.     (IOCCC) be held?  How can I get a copy of the current and
  1479.     previous winning entries?
  1480.  
  1481. A:    Next week.  You missed the deadline.  Tough, sucker.
  1482.  
  1483. 18.12:    Why don't C comments nest?  How am I supposed to comment out
  1484.     code containing comments?  Are comments legal inside quoted
  1485.     strings?
  1486.  
  1487. A:    We believe it has something to do with captivity; C comments in
  1488.     the wild mate and nest normally.  The San Diego Zoo believes it
  1489.     has managed to convince some C comments to nest, but it's hard
  1490.     to tell how much of that is really in the preprocessor, and how
  1491.     much of it is just bovine fecal matter.
  1492.  
  1493. 18.13:    How can I get the ASCII value corresponding to a character, or
  1494.     vice versa?
  1495.  
  1496. A:    chr$(foo);  You would have known this if you had an integer basic
  1497.     in ROM.
  1498.  
  1499. 18.14:    How can I implement sets and/or arrays of bits?
  1500.  
  1501. A:    With linked lists of bitfields.  You may also wish to simply use a
  1502.     large set of constants and some clever use of the switch statement,
  1503.     i.e.:
  1504.  
  1505.         enum { zero, one, two, three };
  1506.  
  1507.         int bitwise_or(int n, int m) {
  1508.             switch (n) {
  1509.             case three:
  1510.                 return three;
  1511.                 break;
  1512.             case two:
  1513.                 switch (m) {
  1514.                 case one: case three: return three; break;
  1515.                 default: return two; break;
  1516.                 }
  1517.                 break;
  1518.             case one:
  1519.                 switch (m) {
  1520.                 case two: case three: return three; break;
  1521.                 default: return one; break;
  1522.                 }
  1523.                 break;
  1524.             default: case zero:
  1525.                 switch (m) {
  1526.                 case one: return one; break;
  1527.                 case two: return two; break;
  1528.                 case three: return three; break;
  1529.                 case zero: default: return zero; break;
  1530.                 }
  1531.                 break;
  1532.             }
  1533.         }
  1534.  
  1535.     Obviously, you'll need to increase this slightly to deal with
  1536.     more than two bits.  This is much more readable than the alleged
  1537.     ``C'' solution:
  1538.  
  1539.         int bitwise_or(int n,int m){return n|m;}
  1540.  
  1541.     Note how the lack of whitespace around operators obscures the
  1542.     functionality of the code.  A clear argument for explicit
  1543.     statement of program logic over arcane operators, if I
  1544.     ever saw one.
  1545.  
  1546.     The enum at the top isn't declared ``const int'', because the
  1547.     resulting ``const poisoning'' would require casts during all of
  1548.     the switch statements.
  1549.  
  1550. 18.15:    What is the most efficient way to count the number of bits which
  1551.     are set in a value?
  1552.  
  1553. A:    Start a counter at zero and add one to it for each bit set.  Some
  1554.     operating systems may provide a call to do this.  For values over
  1555.     INT_MAX/2, start the counter at CHAR_BIT * sizeof(int) and subtract
  1556.     one for each bit not set.
  1557.  
  1558. 18.16:    How can I make this code more efficient?
  1559.  
  1560. A:    Remove the comments; the no-op instructions generated by comments
  1561.     can slow your code down signifigantly.  Similarly, shorten variable
  1562.     names.  Most compilers, to implement pass by value, actually pass
  1563.     the names of variables in the stack; shorter variable names will
  1564.     reduce stack usage, and consequently execution time.  If your compiler
  1565.     has good loop optimization, replace
  1566.  
  1567.         foo();
  1568.     
  1569.     with
  1570.  
  1571.         do {
  1572.             foo();
  1573.         } while (1 != 1);
  1574.     
  1575.     which will likely receive more optimization.
  1576.  
  1577. 18.17:    Are pointers really faster than arrays?  How much do function
  1578.     calls slow things down?  Is ++i faster than i = i + 1?
  1579.  
  1580. A:    Yes.  About 10 ms per call.  Only on machines which feature
  1581.     preincrement addressing.
  1582.  
  1583. 18.18:    This program crashes before it even runs!  (When single-stepping
  1584.     with a debugger, it dies before the first statement in main.)
  1585.  
  1586. A:    You probably declared main as ``void main(void)''.  It's also possible
  1587.     that the first statement in main is abort(); - by the as if rule,
  1588.     the compiler can abort at any time before then, too.  Some compilers
  1589.     have bugs, and will produce buggy code for any module which includes
  1590.     the letters ``a'', ``b'', ``o'', ``r'', and ``t'' in that order before
  1591.     the first function declaration.
  1592.  
  1593. 18.19:    What do ``Segmentation violation'' and ``Bus error'' mean?
  1594.  
  1595. A:    C programs are very territorial, and divide their code into
  1596.     segments.  Violating these segments can trigger riots; similarly,
  1597.     pointers and integral constants are at the front of the bus,
  1598.     wheras arrays, strings, and other second-class data types are
  1599.     required to be at the rear of the bus.  When they start forgetting
  1600.     their places, you can get a bus error.  This is what the whole
  1601.     ``integral'' type thing is about - integrated bussing.
  1602.  
  1603. 18.20:    My program is crashing, apparently somewhere down inside malloc,
  1604.     but I can't see anything wrong with it.
  1605.  
  1606. A:    Your vendor's library is buggy; complain loudly.  Don't send them
  1607.     any example code; they just ask for that so they can steal your
  1608.     trade secrets.
  1609.  
  1610. 18.21:    Does anyone have a C compiler test suite I can use?
  1611.  
  1612. A:    Yes.  Unfortunately, it's probably broken.  It's hard to tell.
  1613.  
  1614. 18.22:    Where can I get a YACC grammar for C?
  1615.  
  1616. A:    You can't; YACC is written in C.
  1617.  
  1618. 18.23:    I need code to parse and evaluate expressions.
  1619.  
  1620. A:    Ask any first year CS student.  You may also wish to use your C
  1621.     compiler.
  1622.  
  1623. 18.24:    I need a sort of an ``approximate'' strcmp routine, for comparing
  1624.     two strings for close, but not necessarily exact, equality.
  1625.  
  1626. A:    Just try comparing pointers near the original pointers.
  1627.  
  1628. 18.25:    Will 2000 be a leap year?
  1629.  
  1630. A:    That's a hard question.  I'd suggest using an encyclopedia, or
  1631.     possibly a dictionary - look up ``yes''.
  1632.  
  1633. 18.26:    How do you pronounce ``char''?
  1634.  
  1635. A:    Like the first word of ``char *''.  The accent is generally on
  1636.     the first syllable.
  1637.  
  1638. 18.27:    Is this FAQ for real?
  1639.  
  1640. A:    *sigh*  I knew someone would ask that.  (Editorial note:  I recieved
  1641.     several corrections to minor factual errors when I first posted this.)
  1642.  
  1643.     If you actually want to know something about C, get a good book
  1644.     (K&R is reccommended), and check out the real FAQ, which is posted
  1645.     monthly in comp.lang.c, and available by anonymous ftp from
  1646.     rtfm.mit.edu.
  1647.  
  1648.     I have a small web page of C stuff:
  1649.         http://www.solon.com/~seebs/c
  1650.     and there is an excellent site at Lysator:
  1651.         http://www.lysator.liu.se/c
  1652.  
  1653.     For extra credit, see if you can figure out what all of the examples
  1654.     really do; most of them will compile, and all of them can be gotten
  1655.     to compile with sufficient #defines.  (I think.)
  1656.  
  1657.  
  1658. Credits:
  1659.  
  1660.     The original comp.lang.c FAQ is maintained by Steve Summit, and
  1661.     many of the questions were stolen from it.  Some of the idiotic
  1662.     misconceptions here are original, but many are from other sources.
  1663.     People have really said or advocated several of these; think about it.
  1664.     The Zork series may well be trademarked, but it was certainly
  1665.     an excellent game.  Some of the mistakes may look similar to things
  1666.     warned against in _C Traps and Pitfalls_.  And, of course, if
  1667.     Dennis Ritchie hadn't written C, these jokes would be much harder
  1668.     to understand.
  1669.  
  1670.     Several people have contributed answers or questions, but I have
  1671.     lost the names in the mists of time.
  1672. -- 
  1673. Peter Seebach - seebs@solon.com - Copyright 1996 Peter Seebach.
  1674. C/Unix wizard -- C/Unix questions? Send mail for help.  No, really!
  1675. FUCK the communications decency act.  Goddamned government.  [literally.]
  1676. The *other* C FAQ - http://www.solon.com/~seebs/c/c-iaq.html
  1677.